package com.hzncc.flowable_diboot.controller.invoicemanage;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.diboot.core.service.DictionaryService;
import com.diboot.core.util.BeanUtils;
import com.diboot.core.util.D;
import com.diboot.core.util.V;
import com.diboot.core.vo.JsonResult;
import com.diboot.core.vo.LabelValue;
import com.diboot.core.vo.Status;
import com.diboot.iam.annotation.OperationCons;
import com.diboot.iam.annotation.BindPermission;
import com.diboot.iam.annotation.Log;
import com.diboot.file.controller.BaseExcelFileController;
import com.diboot.file.excel.listener.ReadExcelListener;
import com.diboot.file.util.ExcelHelper;

import com.diboot.iam.entity.IamUser;
import com.diboot.iam.service.IamUserService;
import com.hzncc.flowable_diboot.delivery.excel.listener.DeliveryDetailImportListener;
import com.hzncc.flowable_diboot.delivery.excel.model.DeliveryDetailImportModel;
import com.hzncc.flowable_diboot.delivery.vo.DeliveryDetailDetailVO;
import com.hzncc.flowable_diboot.entity.SapCustomer;
import com.hzncc.flowable_diboot.entity.invoicemanage.InvoiceRegister;
import com.hzncc.flowable_diboot.dto.invoicemanage.InvoiceRegisterDTO;
import com.hzncc.flowable_diboot.excel.service.MultiSheetExcelImportService;
import com.hzncc.flowable_diboot.exception.BusinessException;
import com.hzncc.flowable_diboot.service.SapCustomerService;
import com.hzncc.flowable_diboot.service.invoicemanage.InvoiceRegisterService;
import com.hzncc.flowable_diboot.vo.invoicemanage.InvoiceProductListVO;
import com.hzncc.flowable_diboot.vo.invoicemanage.InvoiceRegisterDetailVO;
import com.hzncc.flowable_diboot.vo.invoicemanage.InvoiceRegisterListVO;
import com.hzncc.flowable_diboot.excel.listener.InvoiceRegisterImportListener;
import com.hzncc.flowable_diboot.excel.model.InvoiceRegisterImportModel;
import com.hzncc.flowable_diboot.excel.model.InvoiceRegisterExportModel;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import lombok.extern.slf4j.Slf4j;
import jakarta.servlet.http.HttpServletResponse;

import java.util.*;
import java.util.stream.Collectors;

/**
* 开票登记 Excel处理Controller
*
* @author MyName
* @version 1.0
* @date 2024-11-14
 * Copyright © MyCorp
*/
@Slf4j
@RequestMapping("/invoice-manage/invoice-register/excel")
@RestController
@BindPermission(name = "开票登记导入导出", code = "InvoiceRegister")
public class InvoiceRegisterExcelController extends BaseExcelFileController {

    @Autowired
    private InvoiceRegisterService invoiceRegisterService;

    @Resource
    private MultiSheetExcelImportService multiSheetExcelImportService;

    @Resource
    private SapCustomerService sapCustomerService;

    @Resource
    private IamUserService iamUserService;

    @Resource
    private DictionaryService dictionaryService;

    /**
     * 开票登记更新导入
     * @param
     * @return
     * @throws Exception
     */
    @Log(operation = OperationCons.LABEL_UPDATE)
    @BindPermission(name = OperationCons.LABEL_UPDATE, code = OperationCons.CODE_WRITE)
    @PostMapping("/update-import")
    public JsonResult<?> updateImport(@RequestParam("file") MultipartFile file,@RequestParam Map<String,Object> params) throws Exception {
        List<InvoiceRegisterImportModel> list = multiSheetExcelImportService.readSheetBySheetNo(file, InvoiceRegisterImportModel.class, InvoiceRegisterImportListener.class, 1,0);
        List<InvoiceRegisterDetailVO> result = new ArrayList<>();
        for (InvoiceRegisterImportModel importModel : list){
            if (StringUtils.isEmpty(importModel.getId())){
                throw new BusinessException("第"+importModel.getRowIndex()+"行数据ID列为空,无法批量更新");
            }

            InvoiceRegisterDetailVO invoiceRegister = BeanUtils.convert(importModel, InvoiceRegisterDetailVO.class);


            invoiceRegister.setId(importModel.getId());
            InvoiceProductListVO invoiceProduct = new InvoiceProductListVO();
            String recipientLabel = importModel.getRecipientLabel();//合同签订单位
            if (V.notEmpty(recipientLabel)){
                LambdaQueryWrapper<SapCustomer> sapCustomerQuery = new LambdaQueryWrapper<>();
                sapCustomerQuery.eq(SapCustomer::getName,recipientLabel);
                invoiceProduct.setRecipient(sapCustomerService.getSingleEntity(sapCustomerQuery).getId());
            }
            String payTypeLabel = importModel.getPayTypeLabel();
            if (V.notEmpty(payTypeLabel)){
                List<LabelValue> paymentMethod = dictionaryService.getLabelValueList("paymentMethod");
                LabelValue labelValue = paymentMethod.stream().filter(item -> Objects.equals(item.getLabel(), payTypeLabel)).findFirst().get();
                invoiceProduct.setPayType(labelValue.getValue().toString());
            }
            String claimantNo = importModel.getClaimantNo();
            if (V.notEmpty(claimantNo)){
                LambdaQueryWrapper<IamUser> userQuery = new LambdaQueryWrapper<>();
                userQuery.eq(IamUser::getUserNum,claimantNo);
                invoiceRegister.setClaimant(iamUserService.getSingleEntity(userQuery).getId());
            }
            String senderNo = importModel.getSenderNo();
            if (V.notEmpty(senderNo)){
                LambdaQueryWrapper<IamUser> userQuery = new LambdaQueryWrapper<>();
                userQuery.eq(IamUser::getUserNum,senderNo);
                invoiceRegister.setSender(iamUserService.getSingleEntity(userQuery).getId());
            }
            String receiptTypeLabel = importModel.getReceiptTypeLabel();
            if (V.notEmpty(receiptTypeLabel)){
                List<LabelValue> receiptType = dictionaryService.getLabelValueList("receiptType");
                LabelValue labelValue = receiptType.stream().filter(item -> Objects.equals(item.getLabel(), receiptTypeLabel)).findFirst().get();
                invoiceRegister.setReceiptType(labelValue.getValue().toString());
            }
            String invoiceCategoryLabel = importModel.getInvoiceCategoryLabel();
            if (V.notEmpty(receiptTypeLabel)){
                List<LabelValue> invoiceCategory = dictionaryService.getLabelValueList("invoiceCategory");
                LabelValue labelValue = invoiceCategory.stream().filter(item -> Objects.equals(item.getLabel(), invoiceCategoryLabel)).findFirst().get();
                invoiceRegister.setInvoiceCategory(labelValue.getValue().toString());
            }
            String registeredLabel = importModel.getRegisteredLabel();
            if (V.notEmpty(registeredLabel)){
                List<LabelValue> yesNo = dictionaryService.getLabelValueList("yesNo");
                LabelValue labelValue = yesNo.stream().filter(item -> Objects.equals(item.getLabel(), registeredLabel)).findFirst().get();
                invoiceRegister.setRegistered(labelValue.getValue().toString());
            }
            invoiceProduct.setInvoiceRegisterId(importModel.getId())
                    .setSapContractCode(importModel.getSapContractCode())
                    .setContractCode(importModel.getContractCode());
            invoiceRegister.setInvoiceProduct(invoiceProduct);
            result.add(invoiceRegister);
        }
        boolean success = invoiceRegisterService.updateInvoiceRegisterBatch(result);
        return JsonResult.OK(success);
    }

    /**
    * 预览数据
    *
    * @param file
    * @param params
    * @throws Exception
    */
    @Log(operation = "导入预览", businessObj = "InvoiceRegister")
    @BindPermission(name = "导入预览", code = OperationCons.CODE_IMPORT)
    @PostMapping("/preview")
    public JsonResult preview(@RequestParam("file") MultipartFile file, @RequestParam Map<String, Object> params) throws Exception {
        return super.excelPreview(file, params);
    }

    /**
    * 导入预览保存
    *
    * @param params
    * @throws Exception
    */
    @Log(operation = "导入预览保存", businessObj = "InvoiceRegister")
    @BindPermission(name = "导入预览保存", code = OperationCons.CODE_IMPORT)
    @PostMapping("/preview-save")
    public JsonResult previewSave(@RequestParam Map<String, Object> params) throws Exception {
        return super.excelPreviewSave(params);
    }

    /**
    * 上传excel并保存
    *
    * @param file
    * @param params
    * @throws Exception
    */
    @Log(operation = "直接导入", businessObj = "InvoiceRegister")
    @BindPermission(name = "直接导入", code = OperationCons.CODE_IMPORT)
    @PostMapping("/upload")
    public JsonResult upload(@RequestParam("file") MultipartFile file, @RequestParam Map<String, Object> params) throws Exception {
        return super.uploadExcelFile(file, params);
    }

    /**
    * 下载示例文件
    *
    * @param response
    * @throws Exception
    */
    @Log(operation = "导入开票登记示例文件下载", businessObj = "InvoiceRegister")
    @BindPermission(name = "导入开票登记示例文件下载", code = OperationCons.CODE_IMPORT)
    @GetMapping("/download-example")
    public void downloadExample(HttpServletResponse response) throws Exception{
        String fileName = "开票登记导入示例.xlsx";
        ExcelHelper.exportExcel(response, fileName, InvoiceRegisterImportModel.class, null);
    }

    /**
    * 开票登记列表导出
    *
    * @param response
    * @return
    * @throws Exception
    */
    @Log(operation = "导出列表文件", businessObj = "InvoiceRegister")
    @BindPermission(name = "导出列表文件", code = OperationCons.CODE_EXPORT)
    @GetMapping("/export")
    public JsonResult export(InvoiceRegisterDTO invoiceRegisterDto, @RequestParam(value = "columns", required = false) List<String> columns,
        HttpServletResponse response) throws Exception{
        QueryWrapper<InvoiceRegister> queryWrapper = super.buildQueryWrapperByQueryParams(invoiceRegisterDto);
                List<InvoiceRegisterListVO> invoiceRegisterList = invoiceRegisterService.getViewObjectList(queryWrapper, null, InvoiceRegisterListVO.class);
        if (V.isEmpty(invoiceRegisterList)) {
            return new JsonResult(Status.FAIL_OPERATION, "开票登记列表为空，导出失败");
        }
        String fileName = "开票登记列表导出_" + D.today() + ".xlsx";
        List<InvoiceRegisterExportModel> dataList = this.entityList2ExcelList(invoiceRegisterList);
        ExcelHelper.exportExcel(response, fileName, InvoiceRegisterExportModel.class, columns, dataList);
        return null;
    }
    /**
    * 获取表格导出头
    *
    * @return
    */
    @GetMapping("/export-table-head")
    public JsonResult getTableHeaderMap() {
        return new JsonResult<>(ExcelHelper.getTableHeads(InvoiceRegisterExportModel.class));
    }

    /**
    * 实体列表转excel列表
    *
    * @param invoiceRegisterList
    * @return
    */
    private List<InvoiceRegisterExportModel> entityList2ExcelList(List<InvoiceRegisterListVO> invoiceRegisterList) {
        if (V.isEmpty(invoiceRegisterList)) {
            return Collections.emptyList();
        }
        List<InvoiceRegisterExportModel> result = new ArrayList<>();
        for (InvoiceRegisterListVO invoiceRegisterListVO : invoiceRegisterList){
            InvoiceRegisterExportModel convert = BeanUtils.convert(invoiceRegisterListVO, InvoiceRegisterExportModel.class);
            convert.setId(invoiceRegisterListVO.getId());
            convert.setInvoiceCategoryLabel(ObjectUtils.isNotEmpty(invoiceRegisterListVO.getInvoiceCategoryLabel())?invoiceRegisterListVO.getInvoiceCategoryLabel().getLabel():"");
            convert.setReceiptTypeLabel(ObjectUtils.isNotEmpty(invoiceRegisterListVO.getReceiptTypeLabel())?invoiceRegisterListVO.getReceiptTypeLabel().getLabel():"");
            if (ObjectUtils.isNotEmpty(invoiceRegisterListVO.getInvoiceProduct())){
                convert.setContractCode(invoiceRegisterListVO.getInvoiceProduct().getContractCode());
                String payTypeLabel = ObjectUtils.isNotEmpty(invoiceRegisterListVO.getInvoiceProduct().getPayTypeLabel())?invoiceRegisterListVO.getInvoiceProduct().getPayTypeLabel().getLabel():"";
                convert.setPayTypeLabel(payTypeLabel);
                convert.setRecipientLabel(invoiceRegisterListVO.getInvoiceProduct().getRecipientLabel());
            }
            result.add(convert);
        }
//        BeanUtils.convertList(invoiceRegisterList, InvoiceRegisterExportModel.class);
        return result;
    }

    @Override
    protected ReadExcelListener<InvoiceRegisterImportModel> getExcelDataListener() {
        return new InvoiceRegisterImportListener();
    }
}